package com.interview.a_多线程.e_Thread和Object中的重要方.e_两个线程交替打印_0_100_奇偶数;

/**
 * 两个线程 交替打印 奇偶数
 * <p>
 * 一个数据源
 * 一把锁
 * 两个线程
 */
public class Print_1 {
    private static int count = 0;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count <= 100) {
                    synchronized (lock) {
                        if ((count & 1) == 0) {
                            System.out.println(Thread.currentThread().getName() + " " + count + " 偶数");
                            count++;
                        }
                    }
                }
            }
        }, "偶数").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count <= 100) {
                    synchronized (lock) {
                        if ((count & 1) == 1) {
                            System.out.println(Thread.currentThread().getName() + " " + count + " 奇数");
                            count++;
                        }
                    }

                }
            }
        }, "基数").start();
    }
}
